package com.example.moban.module;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;

import com.alibaba.fastjson.JSON;
import com.example.moban.BuildConfig;
import com.example.moban.R;
import com.example.moban.api.HuRequest;
import com.example.moban.beans.VersionInfoBean;
import com.example.moban.ui.activity.SplashActivity;
import com.example.moban.utils.FeiLogUtil;
import com.example.moban.utils.updata.VersionUpdateUtils;
import com.example.moban.view.dialog.VersionDownloadDialog;
import com.example.moban.view.dialog.VersionUpdateDialog;

import com.rzhd.coursepatriarch.common.api.base.BaseObserver;
import com.rzhd.coursepatriarch.common.constants.HttpConstants;
import com.rzhd.coursepatriarch.common.utils.APKVersionCodeUtils;
import com.rzhd.coursepatriarch.common.utils.CommonUtil;
import com.rzhd.coursepatriarch.common.utils.ToastUtils;
import com.rzhd.coursepatriarch.common.utils.permission.AndPermissionUtils;


import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author huling
 * @date: 2019/1/17.
 */
public class VersionUpdateModule implements AndPermissionUtils.AddPermissionCallback,
        VersionUpdateUtils.DownloadFinishInterface{

    private AppCompatActivity activity;
    private Context context;
    private VersionInfoBean.DataBean versionInfoBean;
    private AndPermissionUtils mPermissionUtils;
    private VersionUpdateUtils updateUtils;
    private ProgressDialog progressDialog;
    private OnVersionInfoListener listener;
    private OnInterceptListener interceptListener;

    private VersionUpdateDialog dialog;
    private VersionDownloadDialog downloadDialog;
    /**
     * 是否显示请求进入
     */
    private boolean isShowProgress;
    private boolean isForce;
    private String newVersion, versionInfo;
    private boolean isKillApp;

    public VersionUpdateModule(Context context , AppCompatActivity activity ){
        this.context = context;
        this.activity = activity;
        this.mPermissionUtils = new AndPermissionUtils( context , this );
        updateUtils = new VersionUpdateUtils( context );
        updateUtils.setDownloadFinishInterface( this );
    }

    /**
     * 检查是否需要版本更新
     * @param bean
     * @return
     */
    public boolean isNeedVersionUpdate( VersionInfoBean.DataBean bean ){
        String versionName = CommonUtil.getVersionName(context);
        if(TextUtils.isEmpty( versionName ) || TextUtils.isEmpty( bean.getAndroidVersion() )){
            return false;
        }
        try{
//            String oldVersionName = getVersionName( versionName );
//            String newVersionName = getVersionName( bean.getAndroidVersion() );
            String oldVersionName = versionName;
            String newVersionName = bean.getAndroidVersion();
            if( !TextUtils.isEmpty( oldVersionName ) && oldVersionName.contains( "." )){
                oldVersionName = oldVersionName.replace( ".", "" );
            }
            if( !TextUtils.isEmpty( newVersionName ) && newVersionName.contains( "." )){
                newVersionName = newVersionName.replace( ".", "" );
            }
            int oldValue = Integer.parseInt( oldVersionName );
            int newValue = Integer.parseInt( newVersionName );
            if( newValue > oldValue ){
                return true;
            }
        }catch ( Exception e ){
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 显示版本更新弹窗
     */
    public void showVersionUpdateDialog( String newVersion , String versionInfo , boolean isForce ){
        this.isForce = isForce;
        this.newVersion = newVersion;
        this.versionInfo = versionInfo;
        if( context == null ){
            return;
        }
        dialog = new VersionUpdateDialog();
        dialog.setCancelable( !isForce );
        isKillApp = isForce;
        dialog.setKillAppOnBack( isForce );
        dialog.showDialog(activity.getSupportFragmentManager(),
                String.format( context.getResources().getString( R.string.new_version_text ) , newVersion ),
                versionInfo, context.getResources().getString(R.string.talk_to_you_later_text),
                context.getResources().getString(R.string.update_now_text), isForce , new VersionUpdateDialog.OnDialogListener() {
                    @Override
                    public void confirm() {
                        //开始更新
                        mPermissionUtils.requestPermission(AndPermissionUtils.versionUpdatePermissions);
                    }

                    @Override
                    public void cancel() {
                        if( dialog != null ){
                            dialog.dismiss();
                        }
                        if( interceptListener != null ){
                            interceptListener.onIntercept( false );
                        }
                    }

                    @Override
                    public void onBack() {
                        if( interceptListener != null ){
                            interceptListener.onBack();
                        }
                    }

                    @Override
                    public void dismiss() {
//                        if( interceptListener != null ){
//                            interceptListener.onIntercept( isForce );
//                        }
                    }
                });
    }

    /**
     * 检查版本
     * @param isFromSetting
     */
    public void checkVersion( boolean isFromSetting ){
        getNewVersionInfo( isFromSetting );
    }

    public void checkVersion( VersionInfoBean.DataBean bean ,  boolean isFromSetting ){
        if( bean == null ){
            return;
        }
        boolean needVersionUpdate = isNeedVersionUpdate( bean );
        if( needVersionUpdate ){
            String versionName = getVersionName( bean.getAndroidVersion() );
            showVersionUpdateDialog( versionName ,
                    bean.getAndroidDescription(),
                    (bean.getForceUpdate() == 1 && !isFromSetting) );
        }else{
            //不需要更新直接跳转
            if( interceptListener != null ){
                interceptListener.onIntercept( false );
            }
        }
    }

    /**
     * 获取版本名称
     * @return
     */
    private String getVersionName( String versionName ){
        if( !TextUtils.isEmpty( versionName ) && (!versionName.startsWith( "v" ) && !versionName.startsWith( "V" ))){
            versionName = "v"+versionName;
        }
        return versionName;
    }

    public void getNewVersionInfo(final boolean isFromSetting ){
        if( versionInfoBean == null ){
            //重新获取版本信息
            getNewVersionInfo( isFromSetting , true , null );
        }else{
            checkVersion( versionInfoBean , isFromSetting );
        }
    }

    /**
     * 获取最新版本信息
     */
    public void getNewVersionInfo(final boolean isFromSetting , final boolean isCheckVersion ,
                                  final OnVersionInfoListener listener ){
        this.listener = listener;


        Map<String, Object> params = new HashMap<>();
        params.put( "appType" , "1" );
        params.put( "appVersion" , APKVersionCodeUtils.getVerName(context));
        HuRequest.getInstance().getVersionTypeApiList( params ,

//        HuRequest.getInstance().getVersionTypeApiList( "1" ,
                new BaseObserver<String>( context , isShowProgress ) {
            @Override
            public void onNext(String json) {
                try {
                    if(TextUtils.isEmpty( json )){
                        ToastUtils.longToast( context.getResources().getString( R.string.get_data_fail ));
                        return;
                    }
                    VersionInfoBean versionInfo = JSON.parseObject( json , VersionInfoBean.class );
                    if( versionInfo == null ){
                        ToastUtils.longToast( context.getResources().getString( R.string.get_data_fail ));
                        return;
                    }
                    if( versionInfo.getData() == null ){
                        if( interceptListener != null ){
                            interceptListener.onIntercept( false );
                            return;
                        }
                    }
                    if( versionInfo.getCode() == HttpConstants.RESPONSE_CODE_200 ){
                        handleRequestResult( versionInfo , isCheckVersion , isFromSetting );
                    }
    //                else{
    //                    ToastUtils.longToast( versionInfo.getMessage() );
    //                }
                }catch (Exception e){
                    FeiLogUtil.i("fei",e.toString());
                }
            }
        });
    }

    private void handleRequestResult( VersionInfoBean versionInfo , boolean isCheckVersion , boolean isFromSetting ){
        //获取到版本数据
//        if( versionInfo.getData() == null || versionInfo.getData().size() <= 0 ){
//            return;
//        }
//        VersionUpdateModule.this.versionInfoBean = versionInfo.getData().get( 0 );
//        if( listener != null ){
//            listener.onResult( versionInfo.getData( ).get( 0 ));
//        }
//
//        if( isCheckVersion ){
//            checkVersion( versionInfo.getData().get( 0 ) , isFromSetting );
//        }

        VersionUpdateModule.this.versionInfoBean = versionInfo.getData();
        if( listener != null ){
            listener.onResult( versionInfo.getData( ));
        }

        if( isCheckVersion ){
            checkVersion( versionInfo.getData() , isFromSetting );
        }

    }

    @Override
    public void onGranted(@NonNull List<String> permissions) {
        //判断地址是否正确
        String apkUrl = versionInfoBean.getAndroidUrl();
        if( TextUtils.isEmpty( apkUrl )
                || (!apkUrl.startsWith( "http" ) && !apkUrl.startsWith( "https" ))
                || (!apkUrl.endsWith( "apk" ) && !apkUrl.endsWith( "APK" ))){
            ToastUtils.longToast( context.getResources().getString( R.string.down_load_address_error ));
            return;
        }
//        progressDialog();
//        updateUtils.downloadApk( versionInfoBean != null ? versionInfoBean.getAndroidUrl() : "" );
        if( dialog != null ){
            dialog.dismiss();
        }
        showProgressDialog( apkUrl );
    }

    private void showProgressDialog( String apkUrl ){
        String downloadPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath()
                + File.separator + System.currentTimeMillis();
        downloadDialog = new VersionDownloadDialog();
        downloadDialog.setDialogCancelable( false );
        downloadDialog.showDialog(activity.getSupportFragmentManager(),
                apkUrl , downloadPath , new VersionDownloadDialog.DownloadListener() {
            @Override
            public void completed() {
                //下载完成
                installAPK(new File(downloadPath));
                if( interceptListener  != null ){
                    interceptListener.downloadResult( false );
                }
            }

            @Override
            public void error() {
                //下载错误
                ToastUtils.longToast( context.getResources().getString( R.string.down_load_fail ));
                if( interceptListener  != null ){
                    interceptListener.downloadResult( false );
                }
            }
        });
    }

    protected void installAPK(File file) {
        Log.i("大小", "installAPK: " + file.length());
        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileProvider", file);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    /**
     * 创建强制更新弹窗
     */
    private void progressDialog() {
        progressDialog = new ProgressDialog( context );
        progressDialog.setTitle("正在下载，请稍等...");
        progressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    return true;
                }
                return false;
            }
        });
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();
    }

    @Override
    public void onDenied(@NonNull List<String> permissions) {
        if (versionInfoBean.getForceUpdate() == 1 && context.getClass().getSimpleName().equals(SplashActivity.class.getSimpleName())) {
            //强制更新被取消权限  则不进入app
            activity.finish();
        } else {
//            updateCancel();
        }
    }

    @Override
    public void onComeback() {

    }

    @Override
    public void downloadFinish(int code) {

    }

    public String getVersionInfo() {
        return versionInfo;
    }

    public String getNewVersion() {
        return newVersion;
    }

    public interface OnVersionInfoListener{
        void onResult(VersionInfoBean.DataBean dataBean);
    }

    public interface OnInterceptListener{
        void onIntercept(boolean isIntercept);
        void downloadResult(boolean isSuccess);
        void onBack();
    }

    public void setInterceptListener(OnInterceptListener interceptListener) {
        this.interceptListener = interceptListener;
    }

    public void setShowProgress(boolean showProgress) {
        isShowProgress = showProgress;
    }

    public boolean isForce() {
        return isForce;
    }

    public boolean isKillApp() {
        return isKillApp;
    }
}